import {designComponent, getComponentCls, PropType, reactive, useClasses, useModel} from "@peryl/react-compose";
import {Button, EditProps, iAiConfiguration, Input, StyleProps, useEdit, useStyle} from "plain-design";
import {iAiHistory} from "plain-design/src/packages/components/$ai";
import './chat-box.scss';
import {chatStream} from "./chatStream";
import {uuid} from "@peryl/utils/uuid";
import {lastItem} from "@peryl/utils/lastItem";
import {doNothing} from "@peryl/utils/doNothing";

export const ChatBox = designComponent({
  props: {
    ...EditProps,
    ...StyleProps,
    aiConfig: { type: Object as PropType<iAiConfiguration> },
    messages: { type: Array as PropType<iChatBoxHistory[]> },
    modelValue: { type: String },
  },
  emits: {
    onFinish: () => true,
    onUpdateModelValue: (val?: string) => true,
  },
  setup({ props, event: { emit } }) {

    useEdit();
    useStyle();

    const model = useModel(() => props.modelValue, emit.onUpdateModelValue);

    const state = reactive({
      messages: props.messages ?? [],
      // userContent: '请用表格的方式展示过去10年美债利率变化以及当年纳斯达克的涨幅，现在是2025年',
    });

    const classes = useClasses(() => [
      getComponentCls('chat-box')
    ]);

    const handler = {
      send: async () => {
        state.messages.push({
          id: uuid(),
          role: 'user',
          content: model.value,
        });
        state.messages.push({
          id: uuid(),
          role: 'assistant',
          content: '',
        });
        const assistantMessage = lastItem(state.messages)!;

        await chatStream({
          messages: state.messages,
          onReceiving: ({ chunkText }) => {
            assistantMessage.content += chunkText;
          },
          onFinish: fullText => {
            doNothing();
          }
        });
      },
    };

    return () => (
      <div className={classes.value}>
        <div className="chat-box-message-list">
          {state.messages.map((msg) => (
            <div key={msg.id} className="chat-box-message-item">
              {msg.render ? msg.render() : msg.content}
            </div>
          ))}
        </div>
        <div className="chat-box-message-input">
          <Input textarea v-model={model.value} minHeight={80}/>
          <Button mode="fill" icon="ie-send" shape="round" onClick={handler.send}/>
        </div>
      </div>
    );
  },
});


export interface iChatBoxHistory extends iAiHistory {
  id: string,
  render?: () => any,
}
